package example.demo.netty;

import example.demo.netty.channelHandler.FastJsonDecoder;
import example.demo.netty.channelHandler.FastJsonEncoder;
import example.demo.netty.channelHandler.ServerBusiChannelHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.Map;

/**
 *
 */
@Component
@Slf4j
public class NettyServerStart implements ApplicationListener<ServletWebServerInitializedEvent> {
    @Value("${netty.server.host}")
    String nettyHost;
    @Value("${netty.server.port}")
    Integer nettyPort;

    private Map<String, Channel> channels; // <ip:port, channel>
    private ServerBootstrap bootstrap;
    private Channel channel;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    @Override
    public void onApplicationEvent(ServletWebServerInitializedEvent event) {
        doOpen();
    }

    protected void doOpen() {
        bootstrap = new ServerBootstrap();
        bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
        workerGroup = new NioEventLoopGroup(1,
                new DefaultThreadFactory("NettyServerWorker", true));

        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
                .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        /*剥离接收到的消息的长度字段，拿到实际的消息报文的字节数组*/
                        ch.pipeline().addLast("frameDecoder",
                                new LengthFieldBasedFrameDecoder(65535,
                                        0,
                                        2,
                                        0,
                                        2));
                        /*给发送出去的消息增加长度字段*/
                        ch.pipeline().addLast("frameEncoder",
                                new LengthFieldPrepender(2));
                        //反序列化
                        ch.pipeline().addLast("MessageDecoder", new FastJsonDecoder());
                        //序列化
                        ch.pipeline().addLast("MessageEncoder", new FastJsonEncoder());
                        ch.pipeline().addLast("server-busi", new ServerBusiChannelHandler());
                    }
                });
        ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(nettyHost, nettyPort)).syncUninterruptibly();
        this.channel = channelFuture.channel();
        log.info("NettyServerStart-------------------启动netty-server-succeed");
    }
}
